package org.example.reentrantlock;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhengdp
 * @Description 锁超时测试
 * @Date 2022/11/5 22:16
 * @Created by zhengdp
 */
@Slf4j(topic = "c.LockTimeOutTest")
public class LockTimeOutTest {
    private static ReentrantLock LOCK = new ReentrantLock();
    @SneakyThrows
    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            try {
                if(LOCK.tryLock(2, TimeUnit.SECONDS)){
                    try{
                        log.info("获取到锁");
                    }finally {
                        // 获取锁要释放
                        LOCK.unlock();
                    }
                }else{
                    log.info("未获取到锁，退出线程");
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        },"t1");


        LOCK.lock();
        log.info("主线程获取到锁");
        t1.start();
        // 如果使用 不超时的获取锁方法，那么这个代码将会造成死锁问题
        // 如果使用 tryLock() 就不会造成死锁问题
        t1.join();
        log.info("t1线程执行完毕");
        LOCK.unlock();
        log.info("主线程释放锁");

    }
}
